﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using ExaminationSys.DataAccess.Entity;
using DapperExtensions;
using SQLinq;

namespace ExaminationSys.DataAccess.Repository
{
     public  class PaperSubjectQuestionRepository : Repository<PaperSubjectQuestion>
    {
        public PaperSubjectQuestionRepository(SqlConnection context)
            : base(context)
        {
            db = context;
        }

        private SqlConnection db;

        public override PaperSubjectQuestion GetById(dynamic id)
        {
            return base.ObjectSet.Get<PaperSubjectQuestion>(db, id, null, null);
        }
    }

    public class PaperSubjectQuestionService
    {
        private PaperSubjectQuestionService()
        {
        }

        public List<PaperSubjectQuestion> GetAll()
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.PaperSubjectQuestion.GetList();
                return result.ToList();
            }
        }

        public List<PaperSubjectQuestion> GetPublishList()
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var pg = new PredicateGroup {Operator = GroupOperator.And, Predicates = new List<IPredicate>()};
                pg.Predicates.Add(Predicates.Field<PaperSubjectQuestion>(f => f.Status, Operator.Eq, 1));
                var result = work.PaperSubjectQuestion.GetList(pg);
                return result.ToList();
            }
        }

        public List<PaperSubjectQuestion> GetQuestionList(Guid paperId)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<PaperSubjectQuestion>(f => f.PaperID, Operator.Eq, paperId));
                var result = work.PaperSubjectQuestion.GetList(pg);
                return result.ToList();
            }
        }

        /*
        public List<PaperSubjectQuestion> GetListByPage(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "PaperSubjectQuestion",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<PaperSubjectQuestion>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }
        */

        /// <summary>
        /// 取視图数据
        /// </summary>
        /// <param name="sqlwhere"></param>
        /// <param name="orderbyFiled"></param>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <param name="totalPage"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public List<DBQuestion> GetListByPage(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "View_PaperSubjectQuestion",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<DBQuestion>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }

        public bool CheckQuestionExists(Guid questionid, Guid paperId)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<PaperSubjectQuestion>(f => f.QuestionID, Operator.Eq, questionid));
                pg.Predicates.Add(Predicates.Field<PaperSubjectQuestion>(f => f.PaperID, Operator.Eq, paperId));

                var result = work.PaperSubjectQuestion.GetList(pg);
                return result.ToList().Count > 0;
            }
        }

        public PaperSubjectQuestion GetPaperSubjectQuestion(Guid questionid, Guid paperId)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<PaperSubjectQuestion>(f => f.QuestionID, Operator.Eq, questionid));
                pg.Predicates.Add(Predicates.Field<PaperSubjectQuestion>(f => f.PaperID, Operator.Eq, paperId));

                var result = work.PaperSubjectQuestion.GetList(pg);
                return result.ToList().FirstOrDefault();
            }
        }

        public int SetPaperQuestionOrderIndex(Guid qestionid,Guid paperid, int step)
        {
            if (step == 0) return -1;

            var qustionlist = GetQuestionList(paperid);
            if (qustionlist != null && qustionlist.Count > 0)
            {
                var psq = GetPaperSubjectQuestion(qestionid, paperid);
                if (psq == null) return 0;

                var curOrderIndex = psq.OrderIndex;
                if ((curOrderIndex + step < 1) || (curOrderIndex + step) > GetMaxOrderIndex(paperid))
                {
                    return -1;  //移动出了边界
                }

                var tempList = qustionlist.OrderBy(o => o.OrderIndex);

                //向前移动
                if (step < 0)
                {
                    var needmovelist = tempList.Where(o => o.OrderIndex >= (curOrderIndex + step) && o.OrderIndex <= curOrderIndex).ToList().OrderBy(m=>m.OrderIndex);
                    foreach (var e in needmovelist)
                    {
                        if (e.OrderIndex == curOrderIndex)
                        {
                            e.OrderIndex = curOrderIndex + step;
                        }
                        else
                        {
                            e.OrderIndex += 1;
                        }

                        Update(e);
                    }

                    
                    
                }
                else  //向后移动
                {
                    var needmovelist = tempList.Where(o => o.OrderIndex <= (curOrderIndex + step) && o.OrderIndex >= curOrderIndex).ToList().OrderBy(m => m.OrderIndex);
                    foreach (var e in needmovelist)
                    {
                        if (e.OrderIndex == curOrderIndex)
                        {
                            e.OrderIndex = curOrderIndex + step;
                        }
                        else
                        {
                            e.OrderIndex -= 1;
                        }

                        Update(e);
                    }

                    
                }
            }

            return 1;
        }

        public int GetMaxOrderIndex(Guid paperId)
        {

            using (var db = DataContent.DBServer())
            {
                var result = db.Query<int>(string.Format(" select count(*) from PaperSubjectQuestion where PaperID='{0}'",paperId));
                if (result != null) return result.FirstOrDefault();
                else return 0;
            }

        }

        public int getQuestionOrderIndex(Guid id)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.PaperSubjectQuestion.GetById(id);
                if(result!=null) return result.OrderIndex;
                return 0;
            }
        }

        public PaperSubjectQuestion Get(Guid id)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.PaperSubjectQuestion.GetById(id);
                return result;
            }
        }
        public bool Update(PaperSubjectQuestion entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.PaperSubjectQuestion.Update(entity);
            }
        }
        public dynamic Insert(PaperSubjectQuestion entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.PaperSubjectQuestion.Insert(entity, null);
            }
        }

        public bool Delete(List<string> ids)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"delete from PaperSubjectQuestion where QuestionID=@TmpId",
                                         new[] { new { TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;

                    }
                }
                flag = true;
            }
            return flag;
        }

 


        public bool Lock(List<string> ids, int _status)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"update PaperSubjectQuestion set Status=@status where ID=@TmpId",
                                         new[] { new { status = _status, TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;

                    }
                }
                flag = true;
            }
            return flag;
        }
    }
}